package expend

import (
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"miners-monitor/models/common"

	"context"
)

type ExpendAoModel struct {
	common.BaseModel
	CommonFunc common.CommonFunc
	ExpendDb   ExpendDbModel
}

func (this *ExpendAoModel) Search(filter bson.D, opts *options.FindOptions) Expends {
	opts = opts.SetSort(bson.D{{"Time", -1}})
	result := Expends{}
	result.Data = this.Find(filter, opts)
	result.Total = this.ExpendDb.CountDocuments(filter, options.Count())
	for k, v := range result.Data {
		result.Data[k].TimeString = v.Time.In(common.LocationTime).Format("2006-01-02")
	}
	return result
}

func (this *ExpendAoModel) FindByStruct(filter Expend, opts *options.FindOptions) []Expend {
	filterBsonD, err := this.CommonFunc.StructToBsonD(filter)
	if err != nil {
		panic(err)
	}
	mongoResult := this.ExpendDb.Find(filterBsonD, opts)
	result := []Expend{}
	err = mongoResult.All(context.TODO(), &result)
	if err == mongo.ErrNoDocuments {
		return []Expend{}
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *ExpendAoModel) Find(filter bson.D, opts *options.FindOptions) []Expend {
	mongoResult := this.ExpendDb.Find(filter, opts)
	result := []Expend{}
	err := mongoResult.All(context.TODO(), &result)
	if err == mongo.ErrNoDocuments {
		return []Expend{}
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *ExpendAoModel) FindOne(filter Expend, opts *options.FindOneOptions) Expend {
	mongoResult := this.ExpendDb.FindOne(filter, opts)
	result := Expend{}
	err := mongoResult.Decode(&result)
	if err == mongo.ErrNoDocuments {
		return Expend{}
	} else if err != nil {
		panic(err)
	}
	return result
}


func (this *ExpendAoModel) Upsert(update Expend) {
	this.ExpendDb.Upsert(update)
}

func (this *ExpendAoModel) DeleteOne(update Expend) {
	this.ExpendDb.DeleteOne(update)
}
